//
//  AfterComplaintViewController.m
//  PalmChangtu
//
//  Created by shaorui on 15/6/18.
//  Copyright (c) 2015年 PalmChangtu. All rights reserved.
//

#import "AfterComplaintViewController.h"
#import "ShareUserModel.h"
#import "MainTabbarController.h"
#import "JSONKit.h"
#import "Common.h"
#import "LoadingView.h"
#import "NetWarningView.h"
#import "AFNetworking.h"
#import "BaseUrlConfig.h"
@interface AfterComplaintViewController ()
{
    BOOL  AfterComplaintRequestBool;
}
@end

@implementation AfterComplaintViewController
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        
    }
    return self;
}
-(void)viewDidAppear:(BOOL)animated
{
    
   
}
- (void)viewDidLoad {
    [super viewDidLoad];
    AfterComplaintRequestBool = YES;
    [_v_Top.lalTitel setText:@"售后申诉"];
    
    [_v_Top.btnGoback setHidden:NO];
    _v_Top.parentController = self.navigationController;
    
    
    [_btnSendAction removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    
    [_btnSendAction addTarget:self action:@selector(btnSendAction:) forControlEvents:UIControlEventTouchUpInside];

    [_btnTellAction removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    
    [_btnTellAction addTarget:self action:@selector(tapCallNumber:) forControlEvents:UIControlEventTouchUpInside];
    [_textViewConnet becomeFirstResponder];
    [self.view addSubview:self.textViewConnet];
    [self.view addSubview:self.tab];
    // Do any additional setup after loading the view from its nib.
}

-(void)btnSendAction:(UIButton *)button
{
    
    
    
    if (strIsEmpty(self.textViewConnet.text)) {
        [[MainTabbarController ShareTabBarController]showMessage:@"申诉内容不能为空"];
        return ;
    }
    
    
    
    ShareUserModel * shareUser  = [ShareUserModel shareUserModel];

    
    NSDictionary *params = @{
                             
                             @"complainantId":[NSString stringWithFormat:@"%@",@"231"],
                             @"orderId":[NSString stringWithFormat:@"231"],
                             @"commodityId":[NSString stringWithFormat:@"%@",@"2312"],
                             @"content":[NSString stringWithFormat:@"%@",self.textViewConnet.text],
                             
                             @"loginName":[NSString stringWithFormat:@"%@",shareUser.user.phone],
                             
                             @"userId":[NSString stringWithFormat:@"%@",shareUser.user.user_id],

                             @"sessionId":[NSString stringWithFormat:@"%@",shareUser.user.sessionId]
                             
                             };
    [self AfterComplaintRequest];

    
    
    
}
#pragma mark - controller events
-(void)tapCallNumber:(UIButton *)button
{
    
    
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"是否拨打"
                                                       delegate:self
                                              cancelButtonTitle:@"取消"
                                         destructiveButtonTitle:nil
                                              otherButtonTitles:@"024－75831313", nil];
    [sheet dismissWithClickedButtonIndex:1 animated:YES];
    [sheet setTag:0];
    [sheet showInView:self.view];
    
}



-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];

    UITouch*touch=[[event allTouches]anyObject];

    UIView * view = [touch view];

    for (UIView * views in view.subviews) {


        if (views == self.tab)

        {

            [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
            NSLog(@"\nfdmldllknegrlkeklnlknklsdaojkhhhuasahuk\n");
        }

    }
    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];




//    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];




}
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    UIView *view = [[super view] hitTest:point withEvent:event];
    [view endEditing:YES];  //隐藏键盘
    return view;
}
//-(id)hitTest:(CGPoint)point withEvent:(UIEvent *)event
//{
//    UIView *hitView = [[super view] hitTest:point withEvent:event];
//    if (hitView == self)
//    {
//        return nil;
//    }
//    else
//    {
//        return hitView;
//    }
//}
//- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
//    [super touchesBegan:touches withEvent:event];
//
//    UIView *touchedView = [[super view] hitTest:point withEvent:event];
//
//    UIView *touchView = self.view;
//    if ([self pointInside:point withEvent:event] &&
//        (!self.view.hidden) &&
//        self.view.userInteractionEnabled &&
//        (self.view.alpha >= 0.01f)) {
//
//        for (UIView *subView in self.view.subviews) {
//            //注意，这里有坐标转换，将point点转换到subview中，好好理解下
//            CGPoint subPoint = CGPointMake(point.x - subView.frame.origin.x,
//                                           point.y - subView.frame.origin.y);
//            UIView *subTouchView = [subView hitTest:subPoint withEvent:event];
//            if (subTouchView) {
//                //找到touch事件对应的view，停止遍历
//                touchView = subTouchView;
//                break;
//            }
//        }
//    }else{
//        //此点不在该View中，那么连遍历也省了，直接返回nil
//        touchView = nil;
//    }
//
//    return touchView;
//}
//
//- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event{
//    return CGRectContainsPoint(self.view.bounds, point);
//}
//
//

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (actionSheet.tag) {
        case 0:
        {
        if (buttonIndex == 0)
            {
            NSURL *phoneNumberURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel:%@", [actionSheet buttonTitleAtIndex:0]]];
            [[UIApplication sharedApplication] openURL:phoneNumberURL];
            }
        }
            break;
        default:
            break;
    }
}






#pragma mark - network request

-(void)AfterComplaintRequest
{
    [[LoadingView shareLoadingView] show];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
    manager.responseSerializer = [AFJSONResponseSerializer serializer];//响应
    NSString *strUrl = [NSString stringWithFormat:@"%@%@",HostServer,buyer_complaintAaction];
    
    
    ShareUserModel * shareUser  = [ShareUserModel shareUserModel];
    /*
     {
     "userId": "13166668087",
     "complainantId": "231",
     "orderId": "2312",
     "commodityId": "854",
     "content": "85asdasdasdasdasdasdsa4",
     "loginName": "13166668888",
     "sessionId": "20150610205529000001"
     }

     说明	英文名	类型
     用户id	userId	varchar
     被申诉商家userId	complainantId	varchar
     订单id	orderId	varchar
     被申诉物品	commodityId	varchar
     申诉内容	content	varchar
     登录名	loginName	varchar
     会话id	sessionId	varchar
     */
    
    NSDictionary *params = @{
                             
                             @"userId":[NSString stringWithFormat:@"%@",shareUser.user.user_id],
                             @"complainantId":[NSString stringWithFormat:@"%@",@"231"],
                             @"orderId":[NSString stringWithFormat:@"231"],
                             @"commodityId":[NSString stringWithFormat:@"%@",@"2312"],
                             @"content":[NSString stringWithFormat:@"%@",@"231223122312231223122312"],
                            @"loginName":[NSString stringWithFormat:@"%@",shareUser.user.phone],

                             
                             @"sessionId":[NSString stringWithFormat:@"%@",shareUser.user.sessionId]
                             
                             };
    
    
    
    
    
    [manager POST:strUrl parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         
         
         //               NSData *doubi = responseObject   ;
         //                   //     JSON格式的NSString转换成NSMutableDictionary
         //               NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
         //
         //               NSError *err = nil;
         //               NSDictionary *dicRespon  = [NSJSONSerialization JSONObjectWithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
         
         NSDictionary * dicRespon = responseObject;
         [self RequestSuccessWith:dicRespon];
         
         [[LoadingView shareLoadingView] dismissAnimated:YES];
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         [[LoadingView shareLoadingView] dismissAnimated:YES];
         [[NetWarningView sharedNetWarningView] show];  //警告网络异常
         //              NSData *doubi = operation.error    ;
         //                  //     JSON格式的NSString转换成NSMutableDictionary
         //              NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
         //
         //              NSError *err = nil;
         //              NSDictionary *dicRespon  = [NSJSONSerialization JSONObjectWithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
         NSLog(@"Error: %@", error);
         NSLog(@"请求出错了: - %@ \n%@",
               [error localizedDescription],
               [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
     }];
    
}

-(void)RequestSuccessWith:(NSDictionary *)dicRespon
{
    
    NSString * code = [dicRespon objectForKey:@"success"];
    if (code.integerValue ==1)
    {
        
        
        
        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];
        
        
        [self.navigationController popViewControllerAnimated:YES ];
        
        
    }
    else
    {
        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];
        
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
